package com.aiyige.page.my.message;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventLogout;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.model.ContactResp;
import com.aiyige.model.Page;
import com.aiyige.model.User;
import com.aiyige.page.main.MainPage;
import com.aiyige.page.my.message.adapter.ContactAdapter;
import com.aiyige.page.my.message.event.EventRefreshCommunicatePageChildren;
import com.aiyige.page.my.message.model.Contact;
import com.aiyige.page.my.message.util.MessageUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.netease.nim.uikit.api.NimUIKit;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContactPage extends BaseFragment implements CommonDataView.RetrofitStub {


    @BindView(R.id.cdv)
    CommonDataView cdv;
    Unbinder unbinder;
    ContactAdapter contactAdapter;
    View contactHeaderLayout;
    View fansLayout;
    View followLayout;
    TextView fansTv;
    TextView followTv;
    Handler mainHandler;

    public ContactPage() {
        setAutoRegisterEventBus(true);
        mainHandler = new Handler(Looper.getMainLooper());
    }

    public static ContactPage newInstance() {
        ContactPage contactPage = new ContactPage();
        return contactPage;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.page_contact, container, false);
        unbinder = ButterKnife.bind(this, view);
        contactAdapter = new ContactAdapter();
        contactAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                NimUIKit.startP2PSession(view.getContext(), contactAdapter.getItem(position).getAccid());
            }
        });
        contactAdapter.setHeaderAndEmpty(true);
        cdv.config(contactAdapter, this);
        cdv.setActionCallback(new CommonDataView.UserActionCallback() {
            @Override
            public void onUserRefresh() {
                requestData();
            }

            @Override
            public void onUserLoadMore() {

            }
        });
        cdv.setErrorHandler(new CommonDataView.ErrorHandler() {
            @Override
            public void onResponseError(String errorMsg) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE)
                        .build());
            }

            @Override
            public void onNetError(String errorMsg) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE)
                        .build());
            }
        });
        initHeader();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void initHeader() {
        contactHeaderLayout = LayoutInflater.from(getContext()).inflate(R.layout.page_contact_header, (ViewGroup) cdv.getRecyclerView().getParent(), false);
        contactAdapter.addHeaderView(contactHeaderLayout);
        fansLayout = contactHeaderLayout.findViewById(R.id.fansLayout);
        fansLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance()
                        .build(ARouterConfig.FansPage)
                        .withString("userId", AccountUtil.getCurrentUser().getId())
                        .navigation();
            }
        });
        followLayout = contactHeaderLayout.findViewById(R.id.followLayout);
        followLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance()
                        .build(ARouterConfig.FollowPage)
                        .withString("userId", AccountUtil.getCurrentUser().getId())
                        .navigation();
            }
        });
        fansTv = contactHeaderLayout.findViewById(R.id.fansTv);
        followTv = contactHeaderLayout.findViewById(R.id.followTv);
    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
        requestData();
    }

    @Override
    protected void onVisible() {
        if (!isFirstLoad() && AccountUtil.isLogin()) {
            cdv.doRefreshRequest();
            requestData();
        }
        super.onVisible();
    }

    @Override
    public void onResume() {
        super.onResume();
        boolean communicatePageVisiable = false;
        try {
            MainPage mainPage = (MainPage) getActivity();
            communicatePageVisiable = mainPage.getCurrentItem() == MainPage.COMMUNICATE_PAGE_INDEX;
        } catch (Exception e) {

        }
        if (communicatePageVisiable && !isFirstLoad() && isFragmentVisible() && AccountUtil.isLogin()) {
            cdv.doRefreshRequest();
            requestData();
        }
    }

    public void requestData() {
        new RequestDataTask(getActivity()).execute();
    }

    public class RequestDataTask extends SafeAsyncTask<Object, Object, Object> {

        public RequestDataTask(Activity activity) {
            super(activity);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            updateView();
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (!(o instanceof Exception)) {
                updateView();
            }
        }


        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .userCenterUsers(AccountUtil.getCurrentUser().getId())
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                User tempUser = JSON.parseObject(json, User.class);
                User user = AccountUtil.getCurrentUser();
                user.setStatisticsBackup(tempUser.getStatisticsBackup());
                AccountUtil.updateCurrentUser(user);
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }

    public void updateView() {
        followTv.setText(StringUtils.getString(R.string.follow_num, StringUtils.formatNum(AccountUtil.getCurrentUser().getStatisticsBackup().getFollowCount())));
        fansTv.setText(StringUtils.getString(R.string.fans_num, StringUtils.formatNum(AccountUtil.getCurrentUser().getStatisticsBackup().getFollowersCount())));
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().mutualFans(currentPage, 15);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Contact> contactList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                List<ContactResp> tempContactRespList = JSON.parseArray(page.getContent(), ContactResp.class);
                for (ContactResp contactResp : tempContactRespList) {
                    ContactResp safeContactResp = new ContactResp(contactResp);
                    contactList.add(Contact.newBuilder()
                            .accid(safeContactResp.getAccid())
                            .avatar(safeContactResp.getAvatar())
                            .id(safeContactResp.getUserId())
                            .name(safeContactResp.getAccount())
                            .build());
                }
            }
            resultList.addAll(contactList);
            EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                    .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_SUCCEED)
                    .itemType(EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE)
                    .build());
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (event.getItemType() == EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE
                && event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH
                && event.getPageType() == MessageUtil.PAGE_TYPE_CONTACT) {
            cdv.showRefreshing();
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (getActivity().isFinishing()) return;
                    cdv.doRefreshRequest();
                    requestData();
                }
            }, 1000);

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventRefreshCommunicatePageChildren event) {
        if (event.getType() == EventRefreshCommunicatePageChildren.TYPE_CONTACT) {
            if (isFragmentVisible()) {
                requestData();
                cdv.doRefreshRequest();
            } else {
                setForceLoad(true);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventLogout event) {
        contactAdapter.setNewData(new LinkedList<Contact>());
        followTv.setText(StringUtils.getString(R.string.follow_num, 0));
        fansTv.setText(StringUtils.getString(R.string.fans_num, 0));
    }
}
